<template>
  <div class="app-container">
    <el-row style="padding-bottom:10px">
      <el-col :span="4">
        <strong style="font-size: 20px;">
          分账日结表
        </strong>
      </el-col>
      <el-col :span="20" align="right">
        <span style="margin-right: .5em">
          <el-switch
            v-model="search.isSettled"
            inactive-text="已分账"
            size="medium"
            @change="filterGenerate();dataProcessor()"
          />
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.date[0]"
            type="date"
            placeholder="日期"
            size="medium"
            :editable="false"
            :clearable="false"
            value-format="yyyy/MM/dd"
            @change="filterGenerate();dataProcessor()"
          />
        </span>
        <span style="margin-right: .5em">
          <el-button :loading="settleLoading" size="medium" type="success" plain @click="settle()">提成确认</el-button>
        </span>
      </el-col>
    </el-row>

    <div class="background">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-document-remove" />
              营收/实收
              <div class="text">
                ￥<span style="color:#ff9900">{{ balance.earns }}</span>
                <span style="color:#19be6b">/{{ balance.actualEarns }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-row>
      <el-table
        v-loading="loading"
        :data="list"
        element-loading-text="加载中..."
        fit
        lazy
        stripe
        show-summary
        :summary-method="getSummaries"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="#" type="index" />
        <el-table-column label="账号" width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.user">{{ scope.row.user.__toString }}</span>
          </template>
        </el-table-column>
        <el-table-column label="代收账号" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.collector">{{ scope.row.collector.__metadata.user.__toString }}({{ scope.row.collector.__toString }})</span>
          </template>
        </el-table-column>
        <el-table-column label="小队" width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.squad">{{ scope.row.squad.__toString }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="员工" width="150" />
        <el-table-column prop="dailyWage" label="日薪" width="150" />
        <el-table-column label="产品">
          <template scope="scope">
            <div v-for="(item,index) in scope.row.statistics" :key="index">
              <span> {{ item.productName }} X {{ item.quantity }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="提成">
          <template scope="scope">
            <div v-for="(item,index) in scope.row.statistics" :key="index">
              <span>{{ item.totalAmount }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productAmount" label="总提成" />
      </el-table>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      settleLoading: false,

      list: [],
      statistics: [],
      staffs: [],
      logs: [],
      search: {
        isSettled: false,
        date: []
      },
      balance: {
        earns: 0,
        actualEarns: 0
      }
    }
  },
  created() {
    const today = new Date()
    const yesterday = new Date(today.getTime() - 86400000)
    const startTime = `${yesterday.getFullYear()}/${yesterday.getMonth() + 1}/${yesterday.getDate()}`
    this.search.date.push(startTime)

    this.filterGenerate()
    this.dataProcessor()
  },
  methods: {
    settle() {
      this.settleLoading = true
      this.axios.get(`/officer/orders`, {
        params: {
          '@filter': `(entity.getStatus() == 2 || entity.getStatus() == 3) && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') && entity.getCreatedTime() <= datetime.get('${this.search.date[1]} 07:59:59')`,
          '@display': `{
              'id': 'entity.getId()'
          }`,
          limit: 10000000
        }})
        .then((res) => {
          // if (res.data.length > 0) {
          //   this.settleLoading = false
          //   this.$alert(`${this.search.date[0]}至${this.search.date[1]}存在未结算订单，请联系收银`, '警告', {
          //     confirmButtonText: '确定',
          //     callback: action => {
          //       location.reload()
          //     }
          //   })
          // } else {
          this.axios.get(`/officer/orders`, {
            params: {
              '@filter': `entity.getStatus() == 4 && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') && entity.getCreatedTime() <= datetime.get('${this.search.date[1]} 07:59:59')`,
              '@display': `{
                    'id': 'entity.getId()'
                }`,
              limit: 10000000
            }})
            .then(async orders => {
              if (orders.data.length > 0) {
                for (var i of orders.data) {
                  try {
                    await this.axios.post(`/officer/orders/${i.id}/settle-execute`)
                  } catch (e) {
                    this.$message.error(`id:${i.id}订单提成结算失败！`)
                  }
                }
                this.settleLoading = false
                this.dataProcessor()
                this.$message.success('提成确认成功！')
              } else {
                this.settleLoading = false
                this.$message.warning('暂无可提成确认订单！')
              }
            })
            .catch(() => {
              this.settleLoading = false
            })
          // }
        })
        .catch(() => {
          this.settleLoading = false
        })
    },
    filterGenerate() {
      const nextDate = new Date(new Date(this.search.date[0]).getTime() + 86400000)
      const endDate = `${nextDate.getFullYear()}/${nextDate.getMonth() + 1}/${nextDate.getDate()}`
      this.search.date[1] = endDate
      console.log(this.search.date)
      this.filter = {
        after: `${this.search.date[0]} 08:00:00`,
        before: `${this.search.date[1]} 07:59:59`,
        settled: this.search.isSettled
      }
    },
    dataProcessor() {
      this.loading = true
      const promise = []
      this.axios.get(`/officer/attendance-logs`, { params: {
        '@select': 'COUNT(entity.staff.id) as nums, entity.staff.id as id, entity.staff.name as name',
        '@groupBy': 'entity.staff.id',
        '@filter': `entity.getDate() >= datetime.get('${this.search.date[0]} 00:00:00')
                 && entity.getDate() <= datetime.get('${this.search.date[1]} 23:59:59')`,
        'limit': 100000000
      }}).then((res) => {
        this.logs = res.data
      })
      // table数据
      promise.push(
        this.axios.get(`/officer/staffs`, { params: {
          '@expands': `["entity.collector"]`,
          'limit': 100000000
        }}).then(res => { this.staffs = res.data })
      )
      promise.push(
        this.axios.get(`/officer/settles/statistics`, { params: this.filter }).then(res => { this.statistics = res.data })
      )
      promise.push(
        this.axios.get(`/officer/stores/statistics`, { params: this.filter }).then((res) => {
          if (res.data) {
            this.balance.earns = res.data.earns
            this.balance.actualEarns = res.data.actualEarns
          } else {
            this.balance.earns = 0
          }
        })
      )
      Promise.all(promise).then(res => {
        const list = []
        for (var i of this.staffs) {
          const item = i
          const statis = this.statistics.find(v => v.staff.id === i.id)
          if (statis) {
            let productAmount = 0
            for (var j of statis.statistics) {
              productAmount += parseFloat(j.totalAmount)
            }
            item.statistics = statis.statistics
            item.productAmount = productAmount.toFixed(2)
            list.push(item)
          } else {
            const check = this.logs.some(v => v.id === i.id)
            if (check) {
              item.statistics = []
              item.productAmount = 0
              list.push(item)
            }
          }
        }
        list.sort((a, b) => {
          return b.productAmount - a.productAmount
        })
        this.list = list
        this.loading = false
      })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (index === 5 || index === 8) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0).toFixed(2)
          // sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })
      return sums
    }
  }
}
</script>

<style lang="scss" scoped>
.background {
  background-color: #f0f0f0;
  padding: 15px 15px 15px 15px;
  border-radius: 10px;
}
.detail {
  background-color: white;
  padding: 20px;
  text-align: center;
}
.text {
  font-size: 24px;
  padding-top: 10px;
}
</style>
